package com.example.mq.demo;

import com.example.mq.common.Consumer;
import com.example.mq.common.MqException;
import com.example.mq.mqclient.Channel;
import com.example.mq.mqclient.Connection;
import com.example.mq.mqclient.ConnectionFactory;
import com.example.mq.mqserver.core.BasicProperties;
import com.example.mq.mqserver.core.ExchangeType;

import java.io.IOException;

/**
 * 这表示消费者类
 */
public class DemoConsumer {
    public static void main(String[] args) throws IOException, InterruptedException, MqException {
        System.out.println("启动消费者");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(9090);

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 创建交换机和队列
        channel.exchangeDelcare("testExchange", ExchangeType.DIRECT,true,false,null);
        channel.queueDelcare("testQueue",true,false,false,null);

        channel.basicConsume("testQueue", true, new Consumer() {
            @Override
            public void handleDelivery(String consumeTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                System.out.println("消费数据开始");
                System.out.println("consumeTag" + consumeTag);
                System.out.println("basicProperties" + basicProperties);
                String bodyString = new String(body,0,body.length);
                System.out.println("body=" + bodyString);
                System.out.println("消费数据结束");
            }
        });
        // 由于消费者不知道生产者生产多少，则就在这里循环模拟一直等待
        while (true){
            Thread.sleep(50);
        }
    }
}
